#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

// 2271. 毯子覆盖的最多白色砖块数
// https://leetcode.cn/problems/maximum-white-tiles-covered-by-a-carpet/description/

class Solution1
{
public:
    int maximumWhiteTiles(vector<vector<int>> &tiles, int carpetLen)
    {
        sort(tiles.begin(), tiles.end(), [](vector<int> &a, vector<int> &b)
             { return a[0] < b[0]; });
        int left = 1;
        int pre = 0;
        int pos = 0;
        int ans = 0;
        int curSum = 0;
        int len = tiles.back()[1];
        for (int i = 1; i <= len; i++)
        {
            if (i > tiles[pos][1])
            {
                pos++;
            }
            if (i <= tiles[pos][1] && i >= tiles[pos][0])
            {
                curSum++;
            }
            while (i - left + 1 > carpetLen)
            {
                if (left > tiles[pre][1])
                {
                    pre++;
                }
                if (left <= tiles[pre][1] && left >= tiles[pre][0])
                {
                    curSum--;
                }
                left++;
            }
            ans = max(ans, curSum);
        }
        return ans;
    }
};

class Solution
{
public:
    int maximumWhiteTiles(vector<vector<int>> &tiles, int carpetLen)
    {
        sort(tiles.begin(), tiles.end(), [](vector<int> &a, vector<int> &b)
             { return a[0] < b[0]; });
        int left = 0;
        int leftIndex = 1;
        int n = tiles.size();
        int ans = 0;
        int sum = 0;
        for (int i = 0; i < n; i++)
        {
            int before = tiles[i][0];
            int after = tiles[i][1];
            sum += after - before + 1;

            int leftPos = after - carpetLen + 1;
            while (leftPos > leftIndex)
            {
                if (leftPos > tiles[left][0] && leftPos <= tiles[left][1])
                {
                    sum -= (leftPos - leftIndex);
                    leftIndex = leftPos;
                    break;
                }
                else
                {
                    sum -= (tiles[left][1] - leftIndex + 1);
                    left++;
                    leftIndex = tiles[left][0];
                }
            }
            ans = max(ans, sum);
        }
        return ans;
    }
};

class Solution
{
public:
    int maximumWhiteTiles(vector<vector<int>> &tiles, int carpetLen)
    {
    }
};

int main()
{
    return 0;
}